/**
 * 1、把数据按一定数量拆分未若干段片段，分片 保证浏览器不会因为处理过多数据卡死
 * 2、创建一个csvArray=[]存放csv片段，改变量将存储一行字符缓冲窜，字符串格式：‘李四,31,产品经理\n’
 * 3、出阿奴关键表头 如：姓名,年龄,职位\n
 * 4、遍历分片：遍历时，通常愮格式化数据，如（格式转换、千分位修正）
 * 5、创建blob对象语法为：const blob = new Blob([String.fromCharCode(0xfeff), ... cvsArray], { type: "text/plain;charset=utf-8"});
 * 6、保存为 CSV 格式的文件：FileSaver.saveAs(blob, '导出.csv');

 */
import Mock from "mockjs";
import FileSaver from "file-saver";
export const getData = async (limit) => {
  return new Promise((resolve, reject) => {
    try {
      const Random = Mock.Random;
      const data = new Array(limit).fill("").map((_, index) => {
        return {
          id: `200820-${index}`,
          username: Random.cname(),
          url: Random.url("http"),
          price: Random.float(0, 110000, 0, 2),
          createAt: Random.datetime("yyyy-MM-dd HH:mm:ss"),
        };
      });
      resolve(data);
    } catch (error) {
      reject(error);
    }
  });
};

// 导出csv格式数据
export const exportCsv = async (
  total = 0,
  size = 1000,
  onProcess = () => {}
) => {
  try {
    if (!total) throw "无数据";
    // 分片
    const step = Math.ceil(total / size);
    // csv缓存
    let csvArray = [];
    // 创建表头
    csvArray.push(["编号", "用户名", "官网", "报价", "创建日期"].join() + "\n");

    // 遍历分片
    for (let i = 0; i < step; i++) {
      await new Promise(async (resolve, reject) => {
        try {
          const data = await getData(size);
          console.log(data);
          const csv = data.map((row) => {
            csvArray.push(Object.values(row).join() + "\n");
          });
          // 统计进度
          const process = (i / step) * 100;
          console.log(`进度${Math.round(process)}%`);
          // 触发监听进度的回调函数
          onProcess(process);
          // 适当暂停,避免页面无法执行渲染
          await new Promise((_resolve) => {
            setTimeout(() => _resolve(true), 50);
          });
          resolve(true);
        } catch (error) {
          reject(error);
        }
      });
    }
    // 遍历完成后固定进度100%
    onProcess(100);

    const blob = new Blob([String.fromCharCode(0xffeff), ...csvArray], {
      type: "textplain;charset=utf-8",
    });
    await FileSaver.saveAs(blob, "file.csv");
    return true;
  } catch (error) {
    return Promise.reject(error);
  }
};
